package com.msb.mall.carts.controller;

import com.msb.mall.carts.interceptor.AuthInterceptor;
import com.msb.mall.carts.service.CartService;
import com.msb.mall.carts.vo.Cart;
import com.msb.mall.carts.vo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.concurrent.ExecutionException;

@Controller
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 获取购物车信息
     * @return
     */
    @GetMapping("/cartList")
    public String getCartList(Model model){
        if (null == AuthInterceptor.threadLocal.get()){
            return "redirect:http://auth.msb.com/login.html";
        }
        Cart cartList = cartService.getCartList();
        model.addAttribute("carts",cartList);
        return "cartList";

    }

    /**
     * 加入购物车
     * @param skuId
     * @param count 购买的商品数量
     * @return
     */
    @RequestMapping("/addCart")
    public String addCart(@RequestParam("skuId") Long skuId, @RequestParam("count") Integer count, Model model) {

        CartItem item = null;
        try {
            item = cartService.addCart(skuId,count);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        model.addAttribute("item",item);
        return "success";
    }

    @RequestMapping("/toTrade")
//    public String toTrade(@RequestParam("skuIds") Long skuIds, @RequestParam("count") Integer count, Model model) {
    public String toTrade() {

        // 更新redis中选中的商品：Check count
//        CartItem item = null;
//        try {
//            item = cartService.addCart(skuId,count);
//        } catch (ExecutionException e) {
//            throw new RuntimeException(e);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }

        return "redirect:http://order.msb.com/toTrade";
    }

}
